package top.scsoul.pas.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import top.scsoul.pas.entity.Clazz;
import top.scsoul.pas.entity.Student;
import top.scsoul.pas.entity.User;
import top.scsoul.pas.repository.*;
import top.scsoul.pas.service.ClazzService;

import javax.transaction.Transactional;
import java.util.List;

@Transactional(rollbackOn = Exception.class)
@Slf4j
@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    ClazzRepository clazzRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    StudentReposotory studentReposotory;
    @Autowired
    ExamInfoRepository examInfoRepository;
    @Autowired
    AchievementRepository achievementRepository;

    @Override
    public Page<Clazz> listClazz(int currentPage, int pageSize) {
        PageRequest pageRequest = PageRequest.of(currentPage - 1, pageSize);
        return clazzRepository.findAll(pageRequest);
    }

    @Override
    public List<Clazz> listClazz() {
        Sort sort = Sort.by("created");
        return clazzRepository.findAll(sort);
    }

    @Override
    public boolean save(String name, String created, long leaderId, Integer type) {
        //检查班级名称
        boolean existClazz = clazzRepository.existsByName(name);
        if (existClazz) {
            return false;
        }
        if (type > 2 || type < 0) {
            type = 2;
        }
        //添加班主任
        User leader = userRepository.getById(leaderId);
        Clazz clazz = new Clazz(null, name, leader, created, type);
        clazzRepository.save(clazz);
        return true;
    }

    @Override
    public Clazz getById(Long id) {
        return clazzRepository.getById(id);
    }

    @Override
    public void update(Long id, String name, String created, long leaderId, Integer type) {
        User leader = userRepository.getById(leaderId);
        Clazz clazz = clazzRepository.getById(id);
        clazz.setName(name);
        clazz.setLeader(leader);
        clazz.setCreated(created);
        clazz.setType(type);
        clazzRepository.save(clazz);
    }

    /**
     * @param id 班级id
     */
    @Transactional(rollbackOn = Exception.class)
    @Override
    public void delete(Long id) {
        List<Student> studentsByClazzId = studentReposotory.getStudentsByClazzId(id);
        studentsByClazzId.forEach(student -> {
            achievementRepository.delByStudentId(student.getId());
        });
        //删除学生
        studentReposotory.deleteByClazzId(id);
        examInfoRepository.deleteByClazzId(id);
        //删除班级
        clazzRepository.deleteById(id);
    }

    @Override
    public long getCountByClazzName(String clazzName) {
        return clazzRepository.getCountByClazzName(clazzName);
    }
}
